<script setup lang="ts">
import { ref } from 'vue';
import type { FormInst } from 'naive-ui';
import { useMessage } from 'naive-ui';
import { useAppStore } from '@/store/modules/app';
import { REQUEST } from '@/api/request';

const message = useMessage();
const emit = defineEmits(['ok']);
const appStore = useAppStore();
const formRefs = ref<FormInst | null>(null);
const showModal: any = ref(false);
const title: any = ref('');
const formValue: any = ref({
  id: '',
  orderNumber: '',
  undelivered: '',
  outbound: ''
});
const maxNumber: any = ref(0);
const open = (data: any) => {
  console.log(data);
  title.value = '出库';
  formValue.value.id = data.id;
  formValue.value.undelivered = data.undelivered;
  formValue.value.orderNumber = data.orderNumber;
  if (data.undelivered <= data.orderNumber) {
    formValue.value.outbound = data.undelivered;
    maxNumber.value = data.undelivered;
  } else {
    formValue.value.outbound = data.orderNumber;
    maxNumber.value = data.orderNumber;
  }
  showModal.value = true;
};
const handleCancel = () => {
  formValue.value = {
    id: '',
    orderNumber: 0,
    undelivered: 0,
    outbound: 0
  };
  showModal.value = false;
};
const handleValidateClick = (e: MouseEvent) => {
  e.preventDefault();
  formRefs.value?.validate(errors => {
    if (!errors) {
      REQUEST.POST('SHOPPINGCHUKU', {
        id: formValue.value.id,
        num: formValue.value.outbound
      }).then((res: any) => {
        console.log(res);
        emit('ok');
        message.success('出库成功！');
      });
    } else {
      message.warning('请完善表单');
    }
  });
};
defineExpose({ open });
</script>

<template>
  <NModal
    v-model:show="showModal"
    :style="{ width: !appStore.isMobile ? '500px' : '100%' }"
    class="custom-card"
    preset="card"
    :title="title"
  >
    <NCard :bordered="false" size="huge" role="dialog" aria-modal="true">
      <template #header-extra>x</template>
      <NForm ref="formRefs" :label-width="80" :model="formValue" :label-placement="!appStore.isMobile ? 'left' : 'top'">
        <NFormItem label="购买数量" path="orderNumber">
          <NInputNumber
            v-model:value="formValue.orderNumber"
            style="width: 100%"
            :disabled="true"
            placeholder="请输入"
          />
        </NFormItem>
        <NFormItem label="出库数量" path="outbound">
          <NInputNumber
            v-model:value="formValue.outbound"
            :max="maxNumber"
            :min="0"
            style="width: 100%"
            placeholder="请输入出库数量"
          />
        </NFormItem>
      </NForm>
      <template #footer>
        <NFlex justify="end">
          <NButton @click="handleCancel">取消</NButton>
          <NButton type="primary" @click="handleValidateClick">确定</NButton>
        </NFlex>
      </template>
    </NCard>
  </NModal>
</template>
